<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head>
  <link href="//gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="Hugo 0.68.3" />

  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Python基础2 &middot; 我的博客</title>

  
  <link type="text/css" rel="stylesheet" href="/my_technology_blog/css/print.css" media="print">
  <link type="text/css" rel="stylesheet" href="/my_technology_blog/css/poole.css">
  <link type="text/css" rel="stylesheet" href="/my_technology_blog/css/syntax.css">
  <link type="text/css" rel="stylesheet" href="/my_technology_blog/css/hyde.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abril+Fatface|PT+Sans:400,400i,700">


  
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/favicon.png">

  
  
</head>

  <body class="theme-base-0b ">
  <aside class="sidebar">
  <div class="container sidebar-sticky">
    <div class="sidebar-about">
      <a href="/my_technology_blog/"><h1>我的博客</h1></a>
      <p class="lead">
       杨博的博客 
      </p>
    </div>

    <nav>
      <ul class="sidebar-nav">
        <li><a href="/my_technology_blog/">Home</a> </li>
        
      </ul>
    </nav>

    <p>&copy; 2021. All rights reserved. </p>
  </div>
</aside>

    <main class="content container">
    <div class="post">
  <h1>Python基础2</h1>
  <time datetime=2020-06-23T17:04:02&#43;0800 class="post-date">Tue, Jun 23, 2020</time>
  <h2 id="字符串格式化">字符串格式化</h2>
<p>Python的字符串格式化有两种方式</p>
<ul>
<li>%格式符方式</li>
<li>format方式</li>
</ul>
<p>事实上，格式化借助的是对象的魔术方法。
实现了<code>__format__</code>的对象才适用于format方式格式化输出，
实现了<code>__str__</code>，<code>__repr__</code>的对象才分别适用于格式符<code>%s</code>和<code>%r</code>输出。
在面向对象章节有给对象定义魔术方法的示例。</p>
<h3 id="格式符"><code>%</code>格式符</h3>
<p>一般格式为 <code>%(name)</code> + <a href="https://docs.python.org/zh-cn/3/library/string.html#formatspec">format_spec</a></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">[[fill]align][sign][<span style="color:#75715e">#][0][width][grouping_option][.precision][type]</span>
</code></pre></div><h4 id="name">name</h4>
<p>可选，用于选择指定的key</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#e6db74">&#34;</span><span style="color:#e6db74">%(name)s</span><span style="color:#e6db74">——</span><span style="color:#e6db74">%(age)d</span><span style="color:#e6db74">&#34;</span><span style="color:#f92672">%</span>{<span style="color:#e6db74">&#39;name&#39;</span>:<span style="color:#e6db74">&#39;宝钟玛琳&#39;</span>,<span style="color:#e6db74">&#39;age&#39;</span>:<span style="color:#ae81ff">17</span>}<span style="color:#e6db74">&#39;宝钟玛琳——17&#39;</span>
</code></pre></div><p>s 和 d 属于 [<code>type</code>]</p>
<p>format_spec规则的常用组分：</p>
<h4 id="sign">sign</h4>
<p>可选，数字和字符串可供选择的值有：</p>
<ul>
<li><code>+</code> 右对齐；正数负数前加正负号</li>
<li><code>-</code> 左对齐；负数前加负号</li>
<li>空格 右对齐；负数前加负号</li>
<li><code>0</code> 右对齐；正数前无符号，负数前加负号；用0填充空白处</li>
</ul>
<h4 id="width">width</h4>
<p>可选，占有宽度</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#e6db74">&#34;</span><span style="color:#e6db74">%(name)+7s</span><span style="color:#e6db74">——</span><span style="color:#e6db74">%(age)-5d</span><span style="color:#e6db74">&#34;</span><span style="color:#f92672">%</span>{<span style="color:#e6db74">&#39;name&#39;</span>:<span style="color:#e6db74">&#39;宝钟玛琳&#39;</span>,<span style="color:#e6db74">&#39;age&#39;</span>:<span style="color:#ae81ff">17</span>}<span style="color:#e6db74">&#39;   宝钟玛琳——17   &#39;</span>
</code></pre></div><h4 id="precision">.precision</h4>
<p>可选，小数点后保留的位数 默认6位</p>
<h4 id="type">type</h4>
<p>类型，必选</p>
<p>任意对象：</p>
<ul>
<li><code>%s</code> 字符串 (采用<code>str()</code>的显示)</li>
<li><code>%r</code> 字符串 (采用<code>repr()</code>的显示)</li>
<li><code>%c</code> 单个字符</li>
</ul>
<p>字符串和整数：</p>
<ul>
<li><code>%b</code> 二进制整数</li>
<li><code>%%</code> 字符”%”转义</li>
</ul>
<p>数字：</p>
<ul>
<li><code>%d</code> 十进制整数</li>
<li><code>%i</code> 十进制整数</li>
<li><code>%o</code> 八进制整数</li>
<li><code>%x</code> 十六进制整数</li>
<li><code>%e</code> 指数 (基底写为e)</li>
<li><code>%E</code> 指数 (基底写为E)</li>
<li><code>%f</code> 浮点数</li>
<li><code>%F</code> 浮点数，与上相同</li>
<li><code>%g</code> 科学计数法(e)或浮点数 (根据显示长度)</li>
<li><code>%G</code> 科学计数法(E)或浮点数 (根据显示长度)</li>
<li><code>%%</code> 字符”%”</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#e6db74">&#39;——</span><span style="color:#e6db74">%(p).2f</span><span style="color:#e6db74">&#39;</span><span style="color:#f92672">%</span>{<span style="color:#e6db74">&#39;p&#39;</span>:<span style="color:#ae81ff">0.1</span><span style="color:#f92672">+</span><span style="color:#ae81ff">0.2</span>}<span style="color:#e6db74">&#39;——0.30&#39;</span><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#e6db74">&#39;——</span><span style="color:#e6db74">%(p).2g</span><span style="color:#e6db74">&#39;</span><span style="color:#f92672">%</span>{<span style="color:#e6db74">&#39;p&#39;</span>:<span style="color:#ae81ff">0.1</span><span style="color:#f92672">+</span><span style="color:#ae81ff">0.2</span>}<span style="color:#e6db74">&#39;——0.3&#39;</span>
</code></pre></div><h3 id="终端字体颜色">终端字体颜色</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#e6db74">&#34;&#34;&#34;#格式：　　设置颜色开始 ：</span><span style="color:#ae81ff">\033</span><span style="color:#e6db74">[显示方式;前景色;背景色m　　#说明：前景色            背景色           颜色---------------------------------------30                40              黑色31                41              红色32                42              绿色33                43              黃色34                44              蓝色35                45              紫红色36                46              青蓝色37                47              白色显示方式           意义-------------------------0                终端默认设置1                高亮显示4                使用下划线5                闪烁7                反白显示8                不可见&#34;&#34;&#34;</span><span style="color:#75715e">#例子：\033[1;31;40m    #1-高亮显示 31-前景色红色  40-背景色黑色\033[0m          #采用终端默认设置，即取消颜色设置</span>
</code></pre></div><p>可以使用第三方模块termcolor来简化语句：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> termcolor <span style="color:#f92672">import</span> coloredprint(colored(<span style="color:#e6db74">&#34;helloworld&#34;</span>, <span style="color:#e6db74">&#34;red&#34;</span>))
</code></pre></div><p>第三方模块在使用前需要用pip安装</p>
<p>系统支持</p>
<p>Windows7及以下无法解析颜色代码
使用termcolor模块也无效
可以使用第三方模块colorama来显示颜色</p>
<p>colorama模块兼容更好：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> colorama <span style="color:#f92672">import</span>  init, Foreinit(autoreset<span style="color:#f92672">=</span>False) <span style="color:#75715e">#给True的时候print时无需+Fore.RESETprint(Fore.RED + &#34;helloworld&#34; + Fore.RESET)</span>
</code></pre></div><h3 id="内置函数format">内置函数<code>format()</code></h3>
<p>内置函数<code>format</code>(<em>value</em>[, <em>format_spec</em>])
第二个参数即format_spec格式规格迷你语言
实现了魔术方法<code>__format__</code>的对象都可以使用</p>
<p>以数字对象的格式化为例：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> format(<span style="color:#ae81ff">12</span>,<span style="color:#e6db74">&#39;+.3f&#39;</span>) <span style="color:#75715e">#保留3位小数&#39;+12.000&#39;&gt;&gt;&gt; format(3,&#39;b&#39;) #二进制转化&#39;11&#39;</span>
</code></pre></div><p>其他实现了魔术方法<code>__format__</code>的对象，这里以<code>datetime.time</code>对象为例：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> night <span style="color:#f92672">=</span> datetime<span style="color:#f92672">.</span>time(<span style="color:#ae81ff">22</span>,<span style="color:#ae81ff">30</span>,tzinfo<span style="color:#f92672">=</span>datetime<span style="color:#f92672">.</span>timezone(<span style="color:#f92672">...</span>     datetime<span style="color:#f92672">.</span>timedelta(hours<span style="color:#f92672">=</span><span style="color:#ae81ff">8</span>), name <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;北京&#39;</span>))<span style="color:#f92672">&gt;&gt;&gt;</span> format(night,<span style="color:#e6db74">&#39;现在是%Z时间%H点%M分&#39;</span>)<span style="color:#e6db74">&#39;现在是北京时间22点30分&#39;</span>
</code></pre></div><p><code>datetime</code>模块后续会介绍。</p>
<h3 id="strformat"><code>str.format()</code></h3>
<p>涉及到函数的传参方式，将在后面章节介绍。</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#e6db74">&#39; {}  {}  {} &#39;</span><span style="color:#f92672">.</span>format(a,b,c)     <span style="color:#e6db74">&#39; {0}  {1}  {2} &#39;</span><span style="color:#f92672">.</span>format(a,b,c)<span style="color:#e6db74">&#39; {0}  {1}  {2} &#39;</span><span style="color:#f92672">.</span>format(<span style="color:#f92672">*</span>[a,b,c])<span style="color:#e6db74">&#39; {a}  {b}  {c} &#39;</span><span style="color:#f92672">.</span>format(a<span style="color:#f92672">=</span>a,b<span style="color:#f92672">=</span>b,c<span style="color:#f92672">=</span>c)<span style="color:#e6db74">&#39; {a}  {b}  {c} &#39;</span><span style="color:#f92672">.</span>format(<span style="color:#f92672">**</span>{<span style="color:#e6db74">&#34;a&#34;</span>:a,<span style="color:#e6db74">&#34;b&#34;</span>:b,<span style="color:#e6db74">&#34;c&#34;</span>:c})
</code></pre></div><p><code>{!s}</code>是默认的</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#e6db74">&#39;{!s}、{!a}、{!r}&#39;</span> <span style="color:#75715e">#分别表示str、ascii和repr方法。</span>
</code></pre></div><p>实现了魔术方法<code>__format__</code>的对象可以使用冒号 <code>: format_spec</code></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#e6db74">&#39;0x{:x}&#39;</span><span style="color:#f92672">.</span>format(<span style="color:#ae81ff">255</span>)<span style="color:#e6db74">&#39;0xff&#39;</span>
</code></pre></div><p>以<code>datetime.time</code>对象为例的其他实现了魔术方法<code>__format__</code>的对象：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#e6db74">&#39;现在是{:%Z}时间{:%H}点{:%M}分&#39;</span><span style="color:#f92672">.</span>format(night,night,night)<span style="color:#e6db74">&#39;现在是北京时间22点30分&#39;</span>
</code></pre></div><h3 id="f字符串">f字符串</h3>
<p>在python3.6以上，<code>str.format()</code>可以直接使用<strong>f字符串</strong>的写法
用<code>f'{a}{b}{c}'</code>即可代替<code>'{a}{b}{c}'.format(a=a,b=b,c=c)</code>。
f字符串中不允许使用<code>\</code>转义字符。</p>
<p>与<code>%</code>格式符的不同：
Sign对齐使用<code>&lt;</code>，<code>&gt;</code> 和 <code>^</code> 而不是 <code>+</code> 和 <code>-</code></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#e6db74">&#39;</span><span style="color:#e6db74">%-6d</span><span style="color:#e6db74">000&#39;</span><span style="color:#f92672">%</span><span style="color:#ae81ff">233233</span>   <span style="color:#ae81ff">000</span><span style="color:#f92672">&gt;&gt;&gt;</span> f<span style="color:#e6db74">&#39;{233:&lt;6d}000&#39;</span><span style="color:#ae81ff">233</span>   <span style="color:#ae81ff">000</span>
</code></pre></div><p>以<code>datetime.time</code>对象为例的其他实现了魔术方法<code>__format__</code>的对象：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> f<span style="color:#e6db74">&#39;现在是{night:%Z}时间{night:%H}点{night:%M}分&#39;&#39;现在是北京时间22点30分&#39;</span>
</code></pre></div><p>在python3.8以上</p>
<p>f字符串中可以直接使用说明符<code>=</code>调试，</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> python <span style="color:#f92672">=</span> <span style="color:#ae81ff">3.8</span>	<span style="color:#f92672">&gt;&gt;&gt;</span> f<span style="color:#e6db74">&#34;{python=}&#34;</span>	<span style="color:#e6db74">&#39;python=3.8&#39;</span>
</code></pre></div><h3 id="内置函数str和repr">内置函数<code>str()</code>和<code>repr()</code></h3>
<p><code>str()</code>不止是构造函数（<code>class</code>）实例化一个<code>str</code>对象，
<code>str(o)</code>它也是对参数对象进行魔术方法的调用：<code>o.__str__()</code>，将参数转换为了<code>str</code>对象
无论是<code>print(o)</code>，<code>f'{o}'</code>, <code>&quot;%s&quot;%o</code>，它们都是对魔术方法 <code>o.__str__()</code>的调用</p>
<hr>
<p>而<code>repr(o)</code>，<code>f'{o!r}'</code>, <code>&quot;%r&quot;%o</code>则是对魔术方法 <code>o.__repr__()</code>的调用，
它会以字面量的形式呈现对象，即字符串带有引号，列表变成<code>'['+ repr(成员) + ',]'</code>
<strong>f字符串</strong>中<code>f'{o=}'</code>就相当于<code>f'o={repr(o)}'</code></p>

</div>


    </main>

    
  </body>
</html>
